package com.kitten.dataAlign.consumer;

import com.kitten.dataAlign.constants.MQConstants;
import com.kitten.dataAlign.constants.RedisKeyConstants;
import com.kitten.dataAlign.constants.TableConstants;
import com.kitten.dataAlign.domain.mapper.InsertRecordMapper;
import com.kitten.dataAlign.model.dto.NoteOperateMqDTO;
import com.kitten.framework.common.utils.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Objects;

/**
 * @author kitten
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "kittenBook_group_data_align_" + MQConstants.TOPIC_NOTE_OPERATE,
    topic = MQConstants.TOPIC_NOTE_OPERATE
)
public class TodayNoteOperateIncrement2DBConsumer implements RocketMQListener<String> {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${table.shards}")
    private int tableShards;
    @Autowired
    private InsertRecordMapper insertRecordMapper;

    @Override
    public void onMessage(String body) {
        log.info("笔记发布/删除 日增量数据变更 消费");
        // 1. 布隆过滤器判断该日增量数据是否已经记录
        NoteOperateMqDTO dto = JsonUtils.parseObject(body, NoteOperateMqDTO.class);
        if (Objects.isNull(dto)) {
            return;
        }
        Long creatorId = dto.getCreatorId();

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  // 今日日期字符串

        String key = RedisKeyConstants.buildBloomUserNotePublishCountKey(date);     // bloom:dataAlign:user:note:publishCount:20250101
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource("/lua/notePublishCount/bloom_today_user_note_count_check.lua")));

        Long result = redisTemplate.execute(script, Collections.singletonList(key), creatorId);
        if (Objects.equals(result, 0L)) {
            // 2. 若无，才会落库，减轻数据库压力
            // 将日增量变更数据，写入日增量表中
            // - t_data_align_note_publish_count_temp_日期_分片序号
//            long userIdHashKey = creatorId % tableShards;
//            // 写入日增量表 suffix: 20250101_分片序号  creatorId: 用户id
//            insertRecordMapper.insert2DataAlignUserNotePublishCountTempTable(TableConstants.buildTableNameSuffix(date, userIdHashKey), creatorId);
//            // 3. 数据库写入成功后，再添加布隆过滤器中
//            RedisScript<Long> bloomAddScript = RedisScript.of("return redis.call('BF.ADD', KEYS[1], ARGV[1])", Long.class);
//            redisTemplate.execute(bloomAddScript, Collections.singletonList(key), creatorId);

        }

    }
}
